package mystack;

import java.util.Arrays;

public class MyStack<E>{
    private Object[] elem;
    private int usedSize;

    public MyStack() {
        this.elem = new Object[5];
    }

    public MyStack(int size){
        if (size <= 0){
            throw new RuntimeException("不可小于0");
        }
        this.elem = new Object[size];
    }

    public boolean isFull(){
        return this.usedSize == this.elem.length;
    }

    public void push(E val){
        if (isFull()){
            this.elem = Arrays.copyOf(this.elem, this.elem.length * 2);
        }
        this.elem[usedSize] = val;
        this.usedSize++;//别忘了++
    }

    public E pop(){
        if (empty()){
            throw new RuntimeException("栈为空");
        }
        Object tmp = this.elem[this.usedSize - 1];
        this.elem[usedSize - 1] = null;
        this.usedSize--;
        return (E)tmp;
    }

    public E peek(){
        if (empty()){
            throw new RuntimeException("栈为空");
        }
        return (E) this.elem[this.usedSize - 1];
    }

    public boolean empty(){
        return this.usedSize == 0;
    }

}
